﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using KZ.Express.H.Presenter;
using KZ.Utilities;
using KZ.Express.H.ENT;
using System.Reflection;
using System.Resources;

namespace KZ.Express.H
{
    public class BaseView : Form, IBaseView
    {
        #region Fields

        bool _isVisible;
        private StatusStrip statusStrip1;
        private ToolStripStatusLabel tssbMessage;

        protected DataGridView _dataGrid;
        protected BindingSource _bindingSource;
        private ToolStripStatusLabel toolStripStatusLabel1;
        private ToolStripProgressBar tspbProgress;
        private ToolStripStatusLabel lblValue;
        private ToolStripStatusLabel lblMax;
        protected IBasePresenter _presenter;
        protected delegate void DeleteClickHandler(object sender, EventArgs e);
        protected event DeleteClickHandler OnDeleteClick = null;

        #endregion

        #region Protected Methods

        protected virtual void Initialize(DataGridView datagrid)
        {
            _dataGrid = datagrid;
            _dataGrid.AutoGenerateColumns = false;
            _dataGrid.DataSource = _bindingSource;
        }

        protected virtual void LoadData<T>()
        {
            try
            {
                _presenter.LoadDataTable<T>();
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        protected virtual void AddRow()
        {
            DataTable dt = _bindingSource.DataSource as DataTable;
            DataRow row = dt.NewRow();
            dt.Rows.Add(row);
        }

        protected virtual void View_VisibleChanged<T>(object sender, EventArgs e)
        {
            if (this.Visible && !_isVisible)
                LoadData<T>();
            _isVisible = this.Visible;
        }

        protected virtual void Datagrid_Sorted(object sender, EventArgs e)
        {
            int i = 1;
            foreach (DataGridViewRow row in _dataGrid.Rows)
                row.Cells["colNumber"].Value = i++;
        }

        protected virtual void View_OnDeleteClick<T>(object sender, EventArgs e)
        {
            try
            {
                if (ShowMessageBoxConfirm("Bạn có chắc chắn muốn xóa dữ liệu?") == DialogResult.Yes)
                    _presenter.Delete<T>(GetSelecteds());
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        protected virtual void View_OnSearchClick<T>(object sender, EventArgs e)
        {
            LoadData<T>();
        }

        protected virtual void View_OnViewAllClick<T>(object sender, EventArgs e)
        {
            this.Search = null;
            LoadData<T>();
        }

        protected void ShowMessageBoxError(string message)
        {
            MessageBox.Show(message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
        }

        protected DialogResult ShowMessageBoxConfirm(string message)
        {
            return MessageBox.Show(message, "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
        }

        #endregion

        #region Private Methods

        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BaseView));
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.tssbMessage = new System.Windows.Forms.ToolStripStatusLabel();
            this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
            this.tspbProgress = new System.Windows.Forms.ToolStripProgressBar();
            this.lblValue = new System.Windows.Forms.ToolStripStatusLabel();
            this.lblMax = new System.Windows.Forms.ToolStripStatusLabel();
            this.statusStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // statusStrip1
            // 
            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.tssbMessage,
            this.toolStripStatusLabel1,
            this.tspbProgress,
            this.lblValue,
            this.lblMax});
            this.statusStrip1.Location = new System.Drawing.Point(0, 382);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.Size = new System.Drawing.Size(764, 22);
            this.statusStrip1.SizingGrip = false;
            this.statusStrip1.TabIndex = 0;
            this.statusStrip1.Text = "statusStrip1";
            // 
            // tssbMessage
            // 
            this.tssbMessage.ForeColor = System.Drawing.Color.Blue;
            this.tssbMessage.Name = "tssbMessage";
            this.tssbMessage.Size = new System.Drawing.Size(69, 17);
            this.tssbMessage.Text = "tssbMessage";
            // 
            // toolStripStatusLabel1
            // 
            this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
            this.toolStripStatusLabel1.Size = new System.Drawing.Size(680, 17);
            this.toolStripStatusLabel1.Spring = true;
            // 
            // tspbProgress
            // 
            this.tspbProgress.Name = "tspbProgress";
            this.tspbProgress.Size = new System.Drawing.Size(200, 16);
            this.tspbProgress.Visible = false;
            // 
            // lblValue
            // 
            this.lblValue.Name = "lblValue";
            this.lblValue.Size = new System.Drawing.Size(33, 17);
            this.lblValue.Text = "Value";
            this.lblValue.Visible = false;
            // 
            // lblMax
            // 
            this.lblMax.Name = "lblMax";
            this.lblMax.Size = new System.Drawing.Size(34, 17);
            this.lblMax.Text = "/ Max";
            this.lblMax.Visible = false;
            // 
            // BaseView
            // 
            this.ClientSize = new System.Drawing.Size(764, 404);
            this.Controls.Add(this.statusStrip1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "BaseView";
            this.statusStrip1.ResumeLayout(false);
            this.statusStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        #region Constructors

        public BaseView()
        {
            InitializeComponent();

            tssbMessage.Text = String.Empty;
            _bindingSource = new BindingSource();
        }

        #endregion

        #region Public Properties

        public int ObjectID { get; set; }

        public string ActionName { get; set; }

        public int EntityID { get; set; }

        public SearchCriteria Search
        {
            get
            {
                SearchCriteria search = new SearchCriteria();
                PropertyInfo[] properties = this.GetType().GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    object[] obj = property.GetCustomAttributes(typeof(SearchAttribute), true);
                    if (obj.Length > 0)
                        search.Add(property.Name, property.GetValue(this, null));
                }

                return search;
            }
            set
            {
                PropertyInfo[] properties = this.GetType().GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    if (property.CanWrite)
                    {
                        object[] obj = property.GetCustomAttributes(typeof(SearchAttribute), true);
                        if (obj.Length > 0)
                        {
                            if (value == null)
                                property.SetValue(this, null, null);
                            else if (value.ContainsKey(property.Name))
                                property.SetValue(this, value[property.Name], null);
                        }
                    }
                }
            }
        }

        public virtual BaseENT Entity { get; set; }

        public virtual DataTable Table
        {
            get { return _bindingSource.DataSource as DataTable; }
            set
            {
                _bindingSource.DataSource = null;
                _bindingSource.DataSource = value;
            }
        }

        #endregion

        #region Public Methods

        public virtual void Save()
        {
            try
            {
                _presenter.Save();
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        public virtual void Delete()
        {
            if (OnDeleteClick == null) return;
            OnDeleteClick(this, null);
        }

        public virtual void Import() { }

        public virtual void Export() { }

        public virtual void RefreshData() { }

        public virtual int GetSelected()
        {
            if (_dataGrid.SelectedRows.Count > 0)
                return Utility.IntParse(_dataGrid.SelectedRows[0].Cells[0].Value);
            throw new BusinessLogicException("Bạn phải chọn 1 dòng dữ liệu");
        }

        public virtual List<int> GetSelecteds()
        {
            List<int> idList = new List<int>();
            foreach (DataGridViewRow row in _dataGrid.SelectedRows)
                idList.Add(Utility.IntParse(row.Cells[0].Value));

            return idList;
        }

        public void SetMessage(string message)
        {
            tssbMessage.Text = message;
        }

        public bool ShowMessageConfirm(string message)
        {
            return ShowMessageBoxConfirm(message) == DialogResult.Yes;
        }

        public void ChangeProgressBarVisible(bool isVisible)
        {
            tspbProgress.Visible = isVisible;
            lblMax.Visible = isVisible;
            lblValue.Visible = isVisible;
            if (!isVisible)
            {
                tspbProgress.Maximum = 100;
                lblValue.Text = String.Empty;
                lblMax.Text = String.Empty;
            }
        }

        public void ChangeProgressBarMaximum(int value)
        {
            tspbProgress.Maximum = value;
            lblMax.Text = "/  " + value;
            lblValue.Text = "0";
        }

        public void PerformStepProgressBar(int value)
        {
            if (tspbProgress.Value < tspbProgress.Maximum)
            {
                tspbProgress.Value += value;
                lblValue.Text = tspbProgress.Value.ToString();
            }
        }

        public void UpdateValueProgressBar(int value)
        {
            if (tspbProgress.Value < tspbProgress.Maximum)
            {
                tspbProgress.Value = value;
                lblValue.Text = value.ToString();
            }
        }

        #endregion
    }
}
